import { ref, Ref } from 'vue'
import { getCountdownText } from '@/lib/js/utils/tool'

interface CountdownOptions {
    isMillisecond?: boolean
    isAddZero?: boolean
    onEnd?: Function
    onNotStart?: Function
}

interface SetCountdown {
    (startTime: string | number, endTime: string | number, currentTime: string | number, options?: CountdownOptions): void
}

/**
 * @description 获取时间戳
 * @param { string | number } time 时间戳或时间字符串
 * @export { number } 时间戳
 */
function getTimeStamp(time: string | number) {
  if(typeof time === 'number') {
    return time
  }
  return new Date(time).getTime()
}

let timeOutHandler:any = null;
    
/**
 * @description 倒计时hook，用于计算活动倒计时
 * @param { string } defaultText 倒计时初始化之前，默认显示值
 * @export { array } [Ref<string>, SetCountdown]
 */
export const useCountdown = (defaultText = '活动剩余时间：'): [Ref<string>, SetCountdown] => {
  const text = ref(defaultText)
  /**
   * @description 计算倒计时函数
   * @param { string | number } startTime 活动开始时间
   * @param { string | number } endTime 活动结束时间
   * @param { string | number } currentTime 当前时间结束时间
   */
  const countdownFun: SetCountdown = (startTime: string | number, endTime: string | number, currentTime: string | number, options: CountdownOptions = {}) => {
    const { isMillisecond = true, isAddZero, onEnd, onNotStart } = options
    const value = isMillisecond ? 1000 : 1
    startTime = getTimeStamp(startTime)
    endTime = getTimeStamp(endTime)
    currentTime = getTimeStamp(currentTime)
    console.log(new Date(startTime), new Date(endTime), new Date(currentTime))
    clearTimeout(timeOutHandler);

    function doCountdown(timeLong: number) {
      if(timeLong <= 0) {
        onEnd && onEnd()
        return (text.value = '活动已结束')
      }
      text.value = '活动剩余时间：' + getCountdownText(timeLong, isMillisecond, isAddZero)
      timeOutHandler = setTimeout(() => {
        timeLong -= value
        doCountdown(timeLong)
      }, 1000)
    }

    if(currentTime >= endTime) {
      onEnd && onEnd()
      text.value = '活动已结束'
      clearTimeout(timeOutHandler);
    } else if(currentTime < startTime) {
      onNotStart && onNotStart()
      text.value = '活动未开始'
      clearTimeout(timeOutHandler);
    } else { // 活动中
      doCountdown(endTime - currentTime)
    }
  }
  return [text, countdownFun]
}
